﻿using Demo.PetaPoco.Application;
using Demo.PetaPoco.Application.Dtos.User;
using PmSoft.FormSchema;
using Demo.PetaPoco.Application.Services.User;
using Microsoft.AspNetCore.Mvc;
using PmSoft.Data.Abstractions;
using PmSoft.Web.Abstractions;
using PmSoft.Web.Abstractions.Attributes;

namespace Demo.PetaPoco.WebApi.Controllers.System;

[Route("api/system/[controller]")]
[ApiController]
[RestrictAccess(allowedTenantTypes: ["SysUser"])]
public class UserController(UserService userService) : ControllerBase
{
	/// <summary>
	/// 创建用户
	/// </summary>
	/// <param name="createIn">用户创建模型</param>
	/// <returns>创建结果</returns>
	//[MenuAuthorize("user_create")]
	[HttpPost("create")]
	public async ValueTask<ApiResult> CreateAsync(UserCreateModel createIn)
	{
		await userService.CreateAsync(createIn);
		return ApiResult.Ok("创建成功");
	}

	/// <summary>
	/// 更新用户信息
	/// </summary>
	/// <param name="editIn">用户编辑模型</param>
	/// <returns>更新结果</returns>
	//[MenuAuthorize("user_edit")]
	[HttpPut("update")]
	public async ValueTask<ApiResult> UpdateAsync(UserEditModel editIn)
	{
		await userService.UpdateAsync(editIn);
		return ApiResult.Ok("更新成功");
	}

	/// <summary>
	/// 获取编辑表单架构
	/// </summary>
	/// <param name="userId"></param>
	/// <returns></returns>
	[HttpGet("editFormSchema")]
	public async Task<IApiResult> GetEditFormSchemaAsync(int userId = 100)
	{
		var userDetail = await userService.GetUserAsync(userId);
		var editModel = userDetail.MapTo<UserDetailDto, UserEditModel>();
		var formSchema = FormSchemaGenerator.GenerateSchema(editModel);
		return ApiResult.Ok(formSchema);
	}

	/// <summary>
	/// 获取指定用户信息
	/// </summary>
	/// <param name="userId">用户ID</param>
	/// <returns>用户信息</returns>
	[HttpGet("detail")]
	public async ValueTask<UserDetailDto> GetUserDetailAsync(int userId = 1)
	{
		var userDetail = await userService.GetUserAsync(userId);
		return userDetail;
	}

	/// <summary>
	/// 获取指定部门的所有用户
	/// </summary>
	/// <param name="deptId">部门ID</param>
	/// <returns>用户列表</returns>
	[HttpGet("users")]
	public async ValueTask<IEnumerable<UserDto>> GetUsersAsync(int deptId = 1)
	{
		var users = await userService.GetUsersAsync(deptId);
		return users;
	}

	[HttpDelete("delete")]
	public async Task<IApiResult> DeleteAsync(int userId)
	{
		await userService.DeleteAsync(userId);
		return ApiResult.Ok("删除成功");
	}

	/// <summary>
	/// 分页查询用户列表
	/// </summary>
	/// <param name="query">查询条件</param>
	/// <returns>分页后的用户列表</returns>
	[HttpGet("list")]
	//[MenuAuthorize("user_page")]
	public async ValueTask<IPagedList<UserDto>> PageAsync([FromQuery] UserQuery query)
	{
		var users = await userService.UserPagingAsync(query);
		return users;
	}
}
